package org.bbs.demo.reply.api;


import org.bbs.demo.advice.BusinessException;
import org.bbs.demo.common.BBSConstants;
import org.bbs.demo.common.Result;
import org.bbs.demo.reply.dao.DeleteDao;
import org.bbs.demo.reply.dto.ReplyDto;
import org.bbs.demo.utils.jwtutil.JWTutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/comment")
@Transactional //事务声明，表示该类的所有方法都是事务性的，即方法中的所有访问数据库操作构成了一个整体事务，具有原子性
public class ReplyDeleteApi {
    @Autowired
    private DeleteDao deletedao;

    @PostMapping("/reply/delete")
    public Result info(@RequestBody ReplyDto replydto, @RequestHeader String Token) {
        try {

            String userId = JWTutil.getUserID(Token);
            String topicId = deletedao.FindTopicIdFromRId(replydto.getR_id());

            if (deletedao.FindRId(replydto.getR_id()) == null) {
                throw new BusinessException("该回复不存在");
                //return Result.err(BBSConstants.CODE_ERR_BUSINESS, "该回复不存在");
            }
            if (!deletedao.FindReplyUID(replydto.getR_id()).equals(userId)) {
                throw new BusinessException("无法删除不是自己的评论");
                //return Result.err(BBSConstants.CODE_ERR_BUSINESS, "无法删除不是自己的回复");
            }
            deletedao.deleteReply(replydto.getR_id());
            deletedao.updateReplyNum(topicId);
            return Result.OK("回复删除成功");

        } catch (DuplicateKeyException err) {
            throw new BusinessException("删除失败");
            //return Result.err(BBSConstants.CODE_ERR_SYS, "删除失败");

        }
    }
}
